package main.java.singleton;

import java.io.Serializable;

/**
 * 单例模式
 */

public class Singleton implements Serializable {
    private static boolean flag = false;

    private Singleton() {
        synchronized (Singleton.class) {
            if (flag) {

                throw new RuntimeException("不能创建多个对象");
            }
            flag = true;
        }

    }

    public static class SingletHolder {
        private static final Singleton INSTANCE = new Singleton();

    }

    public static Singleton getInstance() {
        return SingletHolder.INSTANCE;
    }

    /**
     * 通过这个方法防止反射破坏单例模式
     *
     * @return
     */
    public Object readResolve() {
        return SingletHolder.INSTANCE;
    }


}
